package com.shihan.sdkdemo;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.DownloadListener;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.Toast;

import androidx.core.content.FileProvider;

import com.qw.soul.permission.SoulPermission;
import com.qw.soul.permission.bean.Permission;
import com.qw.soul.permission.bean.Permissions;
import com.qw.soul.permission.callbcak.CheckRequestPermissionsListener;
import com.shine.meetinglib.logs.LogUtil;
import com.shine.meetinglib.sdk.ShineSdk;
import com.shine.meetinglib.sdk.ShineSdkCallback;
import com.shine.meetinglib.sdk.view.PlayerContainerView;
import com.shine.meetinglib.sdk.view.WeChatView;
import com.shine.meetinglib.ui.CustomSystemWebView;
import com.shine.meetinglib.ui.CustomWebChromeClient;
import com.shine.meetinglib.utils.ImageCompressCallBack;
import com.shine.meetinglib.utils.ImageUtil;
import com.shine.meetinglib.utils.RequestCodes;

import java.io.File;

public class MainActivity extends Activity implements CheckRequestPermissionsListener {
    private static final String TAG = "MainActivity";
    private ShineSdk shineSdk;
    private WebView mWebView;
    private WeChatView mWeChatView;
    private PlayerContainerView mPlayerContainer;
    private long mLastBackPressTime = 0L;
    private String demoUrl = "http://47.94.157.57:9008/deviceUI/demo/index.html?terminalType=4&globalWebRtcConfig=yy";

    //region sdk最简单使用
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(TAG, "onCreate: ");
        setContentView(R.layout.activity_main);

        mWebView = findViewById(R.id.webView);
        mWebView.setWebChromeClient(new CustomWebChromeClient());
        // 申请权限相机、麦克风、存储权限，为简化Demo在Activity启动时就申请
        requestPermission();
    }

    private void initSdk() {
        mWeChatView = findViewById(R.id.we_chat_view);
        mPlayerContainer = findViewById(R.id.player_container);
        shineSdk = ShineSdk.Companion.getInstance(getApplicationContext(), null);
        shineSdk.setWeChatView(mWeChatView);
        shineSdk.setPlayerViewContainer(mPlayerContainer);

        shineSdk.setCallback(new ShineSdkCallback() {
            @Override
            public void loadUrl(String url) {
                if (!TextUtils.isEmpty(url)) {
                    mWebView.loadUrl(url);
                }
            }

            @Override
            public void setWebViewLayerTop() {
                mWebView.bringToFront();
            }
        });
        mWebView.addJavascriptInterface(shineSdk.getJsService(), ShineSdk.INJECT_JS_OBJECT_NAME);
        mWebView.loadUrl(demoUrl);
        // 下载监听，非必要
        mWebView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                shineSdk.downloadFileWithRequestPermission(url, "");
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mWebView != null) {
            mWebView.destroy();
        }
        if (shineSdk != null) {
            shineSdk.onDestroy();
            shineSdk = null;
        }
    }
    // endregion

    // region "选择图库照片"或"拍照"回传给前端Js
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        LogUtil.i(TAG, "onActivityResult requestCode =" + requestCode + ", resultCode =" + resultCode);
        if (mWebView == null) {
            LogUtil.w(TAG, "onActivityResult WebView is null return");
            return;
        }
        final ValueCallback<Uri[]> filePathCallback = getFilePathCallback();
        LogUtil.i(TAG, "onActivityResult (filePathCallback != null): " + (filePathCallback != null));
        switch (requestCode) {
            case RequestCodes.REQUEST_CODE_OPEN_FILE_CHOOSER:
                if (filePathCallback != null) {
                    if (data != null && resultCode == RESULT_OK) {
                        Uri result = data.getData();
                        LogUtil.i(TAG, "onActivityResult OPEN_FILE_CHOOSER result=" + result);
                        filePathCallback.onReceiveValue(new Uri[]{result});
                    } else {
                        filePathCallback.onReceiveValue(null);
                    }
                    resetFilePathCallback();
                }
                break;
            case RequestCodes.REQUEST_CODE_TAKE_PHONE:
                if (filePathCallback == null) {
                    break;
                }
                //图片压缩开始
                ImageUtil.luBanCompress(this, getTokenPhotoPath(), new ImageCompressCallBack() {
                    @Override
                    public void onSucceed(String filePath) {
                        //压缩后的结果回调
                        Uri result;
                        if (Build.VERSION.SDK_INT >= 24) {
                             result = FileProvider.getUriForFile(MainActivity.this,
                                 MainActivity.this.getPackageName() + ".fileprovider",
                                 new File(filePath));
                        } else {
                            result = Uri.parse(filePath);
                        }
                        LogUtil.i(TAG, "ImageCompressCallBack success filePath =" + filePath + ", result =" + result);
                        filePathCallback.onReceiveValue(new Uri[]{result});
                        resetFilePathCallback();
                    }

                    @Override
                    public void onFailure(String msg) {
                        LogUtil.w(TAG, "ImageCompressCallBack Fail msg =" + msg + "");
                        filePathCallback.onReceiveValue(null);
                        resetFilePathCallback();
                    }
                });
                break;
            default:
                break;
        }
    }

    private ValueCallback<Uri[]> getFilePathCallback() {
        WebChromeClient webChromeClient = getWebChromeClient();
        if (webChromeClient instanceof CustomWebChromeClient) {
            return ((CustomWebChromeClient) webChromeClient).getFilePathCallback();
        }
        return null;
    }

    private void resetFilePathCallback() {
        WebChromeClient webChromeClient = getWebChromeClient();
        if (webChromeClient instanceof CustomWebChromeClient) {
            ((CustomWebChromeClient) webChromeClient).setFilePathCallback(null);
        }
    }

    private String getTokenPhotoPath() {
        WebChromeClient webChromeClient = getWebChromeClient();
        if (webChromeClient instanceof CustomWebChromeClient) {
            String path = ((CustomWebChromeClient) webChromeClient).getTokenPhotoPath();
            Log.i(TAG, "getTokenPhotoPath path = " + path);
            return path;
        }
        return null;
    }

    private WebChromeClient getWebChromeClient() {
        WebChromeClient webChromeClient = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            webChromeClient = mWebView.getWebChromeClient();
        } else {
            if (mWebView instanceof CustomSystemWebView) {
                webChromeClient = ((CustomSystemWebView) mWebView).getCustomWebChromeClient();
            }
        }
        return webChromeClient;
    }
    // endregion

    @Override
    public void onBackPressed() {
        mWebView.evaluateJavascript("javascript:onBackPressed()", new ValueCallback<String>() {
            @Override
            public void onReceiveValue(String value) {
                Log.i(TAG, "onBackPressed onReceiveValue:" + value);
                if (Boolean.TRUE.toString().equals(value)) {
                    // 前端处理返回逻辑, nothing to do
                } else {
                    if (System.currentTimeMillis() - mLastBackPressTime <= 2000) {
                        finish();
                    } else {
                        Toast.makeText(MainActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                        mLastBackPressTime = System.currentTimeMillis();
                    }
                }
            }
        });
    }

    private void requestPermission() {
        SoulPermission.getInstance().checkAndRequestPermissions(
            Permissions.build(Manifest.permission.CAMERA,
                Manifest.permission.RECORD_AUDIO, Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE), this);
    }

    @Override
    public void onAllPermissionOk(Permission[] allPermissions) {
        initSdk();
    }

    @Override
    public void onPermissionDenied(Permission[] refusedPermissions) {
        Toast.makeText(this, "请授权后使用", Toast.LENGTH_LONG).show();
    }
}